<template>
  <div class="detail-container">
    <van-nav-bar
      class="bgcolor"
      title="详情"
      safe-area-inset-top
      @click-left="back"
    >
      <template #left>
        <van-icon class="leftIcon" name="arrow-left" size="18" />
      </template>
    </van-nav-bar>

    <div class="Ediandian-card">
      <div class="userAction">
        <div class="action-top-wrap">
          <div class="actionTop">
            <div class="user">
              <div class="avatar">
                <van-image
                  class="avatar-image"
                  round
                  :src="action.author.avatar"
                  fit="cover"
                />
              </div>
              <div class="username-wrap">
                <span class="van-ellipsis username">{{
                  action.author.username
                }}</span>
                <span class="time">{{ action.actTime }}</span>
              </div>
            </div>

            <div class="payAttention">
              <van-button
                v-if="!isPayAttention"
                icon="plus"
                color="#FF8700"
                size="small"
                @click="payAttention"
                >关注</van-button
              >
              <van-button
                v-if="isPayAttention"
                color="#e6e6e6"
                size="small"
                @click="show = true"
              >
                <template slot="icon">
                  <i class="iconfont icon-caidan iconCaidan"></i>
                </template>
                已关注
              </van-button>

              <van-action-sheet
                v-model="show"
                cancel-text="取消"
                :actions="actions"
                @select="onSelect"
              />
            </div>
          </div>

          <div class="action-content">
            {{ action.content }}
          </div>
        </div>

        <div class="action-image">
          <van-grid :column-num="3">
            <van-grid-item
              v-for="(image, index) in action.images"
              :key="index"
              @click="preview($event, index)"
            >
              <van-image :src="image" />
            </van-grid-item>
          </van-grid>
        </div>
        <div class="thumb-wrap">
          <div class="thumb-icon">
            <i
              :class="{ 'Ediandian-icon': isThumb }"
              class="iconfont icon-thumbup"
              @click="thumbup"
            ></i>
            <span class="thumb-count">{{ action.grantCount }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ImagePreview } from "vant";
import {
  thumbUp,
  cancleThumbUp,
  getDetailOfAction,
  payAttention,
  canclePayAttention
} from "@/api/community";
import bus from "@/utils/global-bus";
import { mapState } from "vuex";
export default {
  name: "Detail",

  data() {
    return {
      action: {
        actTime: "",
        author: {
          address: "",
          avatar: "",
          id: null,
          password: "",
          telephone: "",
          username: "",
        },
        content: "",
        grantCount: "",
        id: "",
        images: [],
      },
      isThumb: false,
      isPayAttention: false,
      show: false,
      actions: [{ name: "取消关注" }],
    };
  },

  computed: {
    ...mapState("user", ["user"]),
  },

  activated() {
    this.getAction();
  },

  deactivated() {
    this.$destroy();
  },

  methods: {
    /**
     * 将详情页的数据返回给上级动态页，保持数据的更新
     * 因为动态中，只有是否点赞与点赞量会有变化，其他暂时不做改变，所以只需保持点赞的同步即可
     */
    updateActionAtSameTime(grantCount, isThumb) {
      /**
       * 这里给全局事件总线注册一个事件
       */
      bus.$emit("updateAction", {
        id: this.action.id,
        grantCount: grantCount,
        isThumb: isThumb,
      });
    },

    back() {
      this.$router.go(-1);
    },

    getAction() {
      let data = {
        userId: parseInt(this.$route.params.userId),
        actionId: parseInt(this.$route.params.actionId),
      };

      getDetailOfAction(data).then((res) => {
        this.action = res.data.action;
        this.isThumb = res.data.isThumb;
        this.isPayAttention = res.data.isPayAttention;
        /**
         * 获取到数据后将数据同步到动态页中
         */
        this.updateActionAtSameTime(this.action.grantCount, this.isThumb);
      });
    },

    /**
     * 点赞
     */
    thumbup() {
      /**
       * 首先判断当前点赞状态，已点赞的再点就是取消点赞操作
       * 未点赞的点击才是点赞操作
       */
      //取消点赞
      if (this.isThumb) {
        this.cancleThumbup();
      } else {
        let time = "";
        let date = new Date();
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let hour = date.getHours();
        let minutes = date.getMinutes();
        let second = date.getSeconds();

        time =
          time +
          year +
          "-" +
          month +
          "-" +
          day +
          " " +
          hour +
          ":" +
          minutes +
          ":" +
          second;
        let data = {
          thumber: this.user.id,
          thumbAction: this.action.id,
          time: time,
        };

        thumbUp(data).then((res) => {
          this.isThumb = true;
          this.action.grantCount++;
          this.updateActionAtSameTime(this.action.grantCount, this.isThumb);
           /**
           * 向后端发送点赞消息
           */
          this.websocket.Send("点赞",this.user.username,this.action.author.username,"动态点赞成功")
        });
      }
    },

    /**
     * 取消点赞操作
     */
    cancleThumbup() {
      let data = {
        thumber: this.user.id,
        thumbAction: this.action.id,
      };
      cancleThumbUp(data).then((res) => {
        this.isThumb = false;
        this.action.grantCount--;
        this.updateActionAtSameTime(this.action.grantCount, this.isThumb);
      });
    },

    /**
     * 关注某一用户
     */
    payAttention() {
      let data = {
        fans: this.user.id,
        idol: this.action.author.id,
      };
      payAttention(data).then((res) => {
        this.isPayAttention = true;
        /**
         * 向后端发送关注消息
         */
        this.websocket.Send("关注",this.user.username,this.action.author.username,"关注成功")
      });
    },

    onSelect(item) {
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      if(item.name === '取消关注'){ 
        this.canclePayAttention();
        this.$toast('已取消关注');
        this.show = false;
      }
    },

    /**
     * 取消关注
     */
    canclePayAttention(){ 
        let data = { 
          fans:this.user.id,
          idol:this.action.author.id
        }

        canclePayAttention(data).then(res => { 
            this.isPayAttention = false;
            bus.$emit('delAttentionAction',{
              idol:this.action.author.id
            })
        })

    },

    preview(event, index) {
      ImagePreview({
        images: this.action.images,
        startPosition: index,
      });
    },
  },
};
</script>

<style scoped>
.bgcolor {
  background-color: rgb(153, 217, 157);
  color: #000;
}

.leftIcon {
  color: #000 !important;
  font-size: 18px;
}

.iconCaidan {
  font-size: 15px;
}

.Ediandian-card {
  width: 100%;
  background-color: #fff;
  overflow: hidden;
  margin-bottom: 10px;
}

.userAction {
  width: 350px;
  margin: 0px auto;
  padding-top: 10px;
}

.actionTop {
  height: 45px;
  display: flex;
  justify-content: space-between;
}

.user {
  height: 45px;
  display: flex;
  flex-direction: row;
}

.avatar {
  width: 50px;
}

.avatar-image {
  width: 45px;
  height: 45px;
}

.username {
  font-size: 18px;
  display: block;
  height: 24px;
}

.time {
  font-size: 12px;
  display: block;
  height: 21px;
  line-height: 21px;
}

.action-content {
  padding-top: 5px;
  font-size: 15px;
}

.thumb-wrap {
  display: flex;
  flex-direction: row;
  justify-content: end;
}

.thumb-count {
  font-size: 12px;
}

.Ediandian-icon {
  color: red;
}
</style>